package com.dubbo.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


/**
 * @Description
 * @Author xsd
 * zj : 自定义 RedisTemplate __定义value序列化方式 :redisTemplate.setValueSerializer()-> new RedisObjectSerializer()
 *   _ @Conditional注解，方便程序根据当前环境或者容器情况来动态注入bean、RedisUtil  bean生成。。
 *      RedisUtil  __key 序列 StringRedisSerializer
 *      value序列 _JdkSerializationRedisSerializer 等价于 new SerializingConverter() 底层都是 java 序列化 ByteArrayOutputStream
 *
 */
@ConditionalOnClass({RedisUtil.class})
@Configuration
public class RedisConfig {

    public RedisConfig() {
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(factory);
        RedisSerializer stringSerializer = new StringRedisSerializer();
        RedisSerializer redisObjectSerializer = new RedisObjectSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(redisObjectSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    @Bean
    @ConditionalOnMissingBean
    public RedisUtil redisRepository(RedisTemplate<String, Object> redisTemplate) {
        return new RedisUtil(redisTemplate);
    }

    @Bean
    public KeyGenerator keyGenerator() {
        return (target, method, objects) -> {
            StringBuilder sb = new StringBuilder();
            sb.append(target.getClass().getName());
            sb.append(":" + method.getName() + ":");
            Object[] var4 = objects;
            int var5 = objects.length;

            for(int var6 = 0; var6 < var5; ++var6) {
                Object obj = var4[var6];
                sb.append(obj.toString());
            }

            return sb.toString();
        };
    }
}
